package jh.com.jhappbf.verify;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import jh.com.jhappbf.R;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;

public class VerifyDetail extends AbActivity {

    private View mContentView;
    private View mNetErrorView;
    private AbTitleBar mAbTitleBar;
    private Context mAppContext;
    private TextView mContentTxt;
    private Button mTryAgainBtn;
    private AbDialogFragment mDialogFragment;
    private String mDispatchedId;
    private int mPosition;
    private Button verifyPlanBtn;
    private String mOperate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.detail_content_view, null);
        mNetErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("派车审核");
        mAbTitleBar.setTitleFullWidth();
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackgroundColor(ContextCompat.getColor(this, R.color.orange));
        mAbTitleBar.setTitleTextMargin(10, 0, 10, 0);
        mAbTitleBar.setLogoLine(R.mipmap.line);
        mAppContext = getApplicationContext();
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mContentTxt = mContentView.findViewById(R.id.detail_txt);
        mTryAgainBtn = mNetErrorView.findViewById(R.id.network_error_btn);
        Intent intent = getIntent();
        mDispatchedId = intent.getStringExtra("plandId");
        mPosition = intent.getIntExtra("position", -1);
        mOperate = intent.getStringExtra("operate");
        setTitleRightButton();
        mTryAgainBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setAbContentView(mContentView);
                loadData();
            }
        });

        loadData();
    }

    /**
     * 设置右按钮
     */
    private void setTitleRightButton() {
        View rightBtn;
        if ("未审核".equals(mOperate)) {
            rightBtn = View.inflate(mAppContext, R.layout.title_right_ok_btn_view, null);
            verifyPlanBtn = rightBtn.findViewById(R.id.title_right_ok_btn);
        } else {
            rightBtn = View.inflate(mAppContext, R.layout.title_right_delete_btn_view, null);
            verifyPlanBtn = rightBtn.findViewById(R.id.title_delete_btn);
        }

        mAbTitleBar.addRightView(rightBtn);
        verifyPlanBtn.setOnClickListener(v -> {
            if ("未审核".equals(mOperate)) {
                verifyPlan();
            } else {
                cancelVerifyPlan();
            }
        });
    }

    /**
     * 审核数据
     */
    private void verifyPlan() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "审核中,请稍等...");
        mDialogFragment.setCancelable(false);
        String methodName = "verifyDispatch";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("id");
        params.add("flag");
        params.add("userName");
        values.add(mDispatchedId);
        values.add("1");
        values.add(State.mName);
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null && data.size() > 0) {
                    JSONObject obj = data.get(0);
                    if (obj == null) {
                        return;
                    }
                    String result = obj.optString("result");
                    String memo = obj.optString("memo");
                    AbToastUtil.showToast(VerifyDetail.this, memo);
                    if ("true".equals(result)) {
                        setResultAndQuit();
                    }
                }

            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                setAbContentView(mNetErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }


    /**
     * 取消审核
     */
    private void cancelVerifyPlan() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "取消审核中,请稍等...");
        mDialogFragment.setCancelable(false);
        String methodName = "verifyDispatch";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("id");
        params.add("flag");
        params.add("userName");
        values.add(mDispatchedId);
        values.add("0");
        values.add(State.mName);
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null && data.size() > 0) {
                    JSONObject obj = data.get(0);
                    if (obj == null) {
                        return;
                    }
                    String result = obj.optString("result");
                    String memo = obj.optString("memo");
                    AbToastUtil.showToast(VerifyDetail.this, memo);
                    if ("true".equals(result)) {
                        setResultAndQuit();
                    }
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                setAbContentView(mNetErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }

    /**
     * 返回参数并推出当前设置界面
     */
    private void setResultAndQuit() {
        Intent intent = new Intent();
        intent.putExtra("position", mPosition);
        intent.putExtra("plandId", mDispatchedId);
        setResult(RESULT_OK, intent);
    }

    /**
     * 加载数据
     */
    private void loadData() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.mipmap.ic_load,
                "加载中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

            @Override
            public void onLoad() {
                getDataFromNet();
            }
        });
    }

    /**
     * 调用webService
     */
    private void getDataFromNet() {
        String methodName = "dispatchDetail";
        ArrayList<String> params = new ArrayList<>();
        ArrayList<String> values = new ArrayList<>();
        params.add("dispatchId");
        values.add(mDispatchedId);
        mContentTxt.setText("");
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                List<JSONObject> newListData = JsonHelper.getJsonObjects(response);
                if (newListData != null && newListData.size() > 0) {
                    JSONObject obj = newListData.get(0);
                    String result = obj.optString("result");
                    mContentTxt.setText(result);
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(VerifyDetail.this);
                mDialogFragment.dismiss();
                setAbContentView(mNetErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                params, values, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(mAppContext).addRequest(webService);
    }
}
